package rank

import (
	"github.com/gogf/gf/v2/os/gctx"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/event"
	"xr-game-server/dao/rankdao"
	"xr-game-server/dao/serverdao"
	"xr-game-server/gamecfg"
	"xr-game-server/gameevent"
)

// 天,周,月结算
func initSettlement() {
	event.Sub(gameevent.DayEvent, initDay)
	event.Sub(gameevent.WeekEvent, initWeek)
	event.Sub(gameevent.MonthEvent, initMonth)
}

func initDay(data any) {
	doByType(gamecfg.DaySettlement)
}

func initWeek(data any) {
	doByType(gamecfg.WeekSettlement)
}

func initMonth(data any) {
	doByType(gamecfg.MonthSettlement)
}

func settlementByType(rank *CommonRank) {
	rank.DB.Cache.Clear(gctx.New())
	//发送奖励
	rankCfg := gamecfg.GetRankCfgById(rank.TypeId)
	if len(rankCfg.GetReward()) > common.Zero {
		for _, val := range rank.SortData {
			if len(rankCfg.Reward) == common.Zero {
				continue
			}
			event.Pub(gameevent.AddItemStr, gameevent.NewAddItemData(val.Id, rankCfg.Reward, true))
		}
	}
	rank.SortData = make([]*ObjModel, common.Zero)
}

func doByType(settlementType uint8) {
	//获取所有榜单
	for _, rankCfg := range gamecfg.GetAllRank() {
		//判断所有榜单的结算类型
		if rankCfg.SettlementType == settlementType {
			//开始发送结算
			rankActor.Send(NewSettlementRankEventData(rankCfg.Id), func(msg any) {
				eventData := msg.(*SettlementRankEventData)
				mgr := mgrMap[eventData.RankId]
				servers := serverdao.GetAllServer()
				for _, server := range servers {
					commonRank := mgr.GetRankByServerId(server.ID)
					settlementByType(commonRank)
				}
				//数据库榜单值清0
				rankdao.UpdateRankByTypeId(eventData.RankId)
			})
		}
	}
}
